# coding: utf8

import numpy as np
import pandas as pd
import faker


def demo_series():
    sr1 = pd.Series(range(5))
    sr2 = pd.Series(range(5), index=list('abcde'))
    sr3 = pd.Series(range(5), index=pd.date_range('2000-01-01', '2000-01-05'))
    sr4 = pd.Series({k: v for k, v in zip(list('abc'), range(3))})
    sr41 = pd.Series({k: v for k, v in zip(list('abc'), [1, 2, 3])}, index=['a', 'b', 'x'])
    sr5 = pd.Series(range(3), index=pd.timedelta_range('1 h', '3 h', freq='h'))
    sr6 = pd.Series(range(3), index=pd.Categorical(list('abc')))
    print(
        ">>> sr1 = Series(range(5))\n"
        f"{sr1}\n"
        f">>> sr2 = Series(range(5), index=list('abcde'))\n"
        f"{sr2}\n"
        f">>> sr3 = pd.Series(range(5), index=pd.date_range('2000-01-01', '2000-01-05'))\n"
        f"{sr3}\n"
        ">>> sr4 = pd.Series({k: v for k, v in zip(list('abc'), range(3)})\n"
        f"{sr4}\n"
        ">>> sr41 = pd.Series({k: v for k, v in zip(list('abc'), [1, 2, 3])}, index=['a', 'b', 'x'])\n"
        f"{sr41}\n"
        f">>> sr5 = pd.Series(range(3), pd.timedelta_range('1 h', '3 h', freq='h'))\n"
        f"{sr5}\n"
        f">>> sr6 = pd.Series(range(3), index=pd.Categorical(list('abc')))\n"
        f"{sr6}"
    )


def demo_dataframe():
    fk = faker.Faker('zh_cn')
    data = []
    for j in range(5):
        data.append((fk.name(), fk.random.randint(15, 20), fk.address()))
    for d in data:
        print(d)

    # 构建数据集
    df = pd.DataFrame(data=data, columns=['name', 'age', 'address'])
    df.astype({'name': np.str_, 'age': np.uint8, 'address': np.str_})
    print(df)
    print(df.dtypes)

    # 分解地址列
    addr = df.address.str.split2(' ', expand=True)
    df['addr'] = addr[0]
    df['pb'] = addr[1]
    df = df.drop(columns=['address'])
    print(df)

    # 各列使用不同类型
    df = pd.DataFrame(
        data = {
            'fruit': ['Apple', 'Banana'],
            'price': [3.5, 10.2],
            'selldate': ['2021-05-06', '2021-04-12']})
    df = df.astype({'selldate': np.datetime64})
    print(df)
    print(df.dtypes)


def task():
    data = [("张力", 15, 66.5), ("李明", 25, 78.2), ("何方", 23, 70.6)]
    df = pd.DataFrame(data, columns=['name', 'age', 'weight'])
    print(df)
    print(df.dtypes)


def expand():
    data = [("张力", '15', '66.5'), ("李明", '25', '78.2'), ("何方", 23, 70.6)]
    df = pd.DataFrame(data=data, columns=['name', 'age', 'weight'], index=['1001', '1002', '1003'])
    print("""读入数据：("张力", '15', '66.5'), ("李明", '25', '78.2'), ("何方", 23, 70.6)""")
    print(df)
    print(df.dtypes)

    data = [("张力", '15', '66.5'), ("李明", '25', '78.2'), ("何方", '23', '70.6')]
    df = pd.DataFrame(data=data, columns=['name', 'age', 'weight'], index=['1001', '1002', '1003'])
    print("读入字符串类型数据结果：")
    print(df)
    print(df.dtypes)
    df['name'] = df.name.astype(np.unicode_)
    df['age'] = df.age.astype(np.uint8)
    df['weight'] = df.weight.astype(np.float16)
    print("改变类型后：")
    print(df)
    print(df.dtypes)


if __name__ == '__main__':
    # demo_series()
    # demo_dataframe()
    task()
    expand()
